package com.example.asus.picselector.widget;

import android.annotation.SuppressLint;
import android.app.Activity;

import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

public class RxPermissionManager {

    private static RxPermissionManager permissionManager;

    private PermissionsSuccessCallBack permissionsSuccessCallBack;
    private RxPermissions rxPermissions;

    private RxPermissionManager(){}

    public static RxPermissionManager getIntance(){

        synchronized (RxPermissionManager.class){

            if(permissionManager == null){

                synchronized (RxPermissionManager.class){

                    permissionManager = new RxPermissionManager();
                }

            }

            return permissionManager;
        }
    }

    /**
     * 检查动态权限
     */
    @SuppressLint("CheckResult")
    public void checkPermissions(final Activity activity, String[] needPermissions, final int type){

        if(activity == null)
            return;

        rxPermissions = new RxPermissions(activity);

         rxPermissions.request(needPermissions)
                      .subscribe(new Consumer<Boolean>() {
                          @Override
                          public void accept(Boolean aBoolean) throws Exception {
                              if(aBoolean){  //用户同意该权限
                                  rxPermissions = null;
                                  if(permissionsSuccessCallBack != null){
                                      permissionsSuccessCallBack.success(type);
                                  }
                              }else {  //拒绝权限
                                  // 用户拒绝了该权限，并且选中『不再询问』
                                  rxPermissions = null;
                                  Util.jumpPerssiomSetting(activity,"图片选择器需要存储权限，您需要在设置中打开权限");
                              }
                          }
                      });
    }

    public void setPermissionsSuccessCallBack(PermissionsSuccessCallBack permissionsSuccessCallBack){
        this.permissionsSuccessCallBack = permissionsSuccessCallBack;
    }

    public interface PermissionsSuccessCallBack{
        void success(int type);
    }
}
